import { Button, Card, Table, message, Modal } from "antd";
import React from "react";
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  LoadingOutlined,
} from "@ant-design/icons";
import { useEffect, useState } from "react";
import type { ColumnsType } from "antd/lib/table";
import { Form, Input, Upload } from "antd";
import {
  reqGetBrandList,
  reqRemoveBrand,
  reqAddBrand,
  reqUpdateBrand,
} from "@api/brand/brandList";
import type {
  BrandListType,
  BrandItemType,
} from "@api/brand/model/brandListTypes";
import type { UploadChangeParam } from "antd/es/upload";
import type { RcFile, UploadFile, UploadProps } from "antd/es/upload/interface";

export default function BrandList() {
  // 定义品牌分页列表相关state
  const [current, setCurrent] = useState(1);
  const [pageSize, setPageSize] = useState(5);
  const [total, setTotal] = useState(0);
  const [brandList, setBrandList] = useState<BrandListType>([]);
  const [loading, setLoading] = useState(false);
  const [RowId, setRowId] = useState("");
  const [imageUrl, setImageUrl] = useState<string>("");
  let [form] = Form.useForm();

  // 异步请求获取商品列表显示
  const getBrandList = async (page = current, limit = pageSize) => {
    // console.log(page, limit)
    setLoading(true);
    // 请求获取分页数据
    try {
      const result = await reqGetBrandList(page, limit);
      // 成功后, 更新相关数据, 显示分页列表
      const { total, records } = result;
      setLoading(false);
      setTotal(total);
      setBrandList(records);
      setCurrent(page);
      setPageSize(limit);
    } catch (error) {
      return Promise.reject(error);
    }
  };

  const removeBrand = async (row: BrandItemType) => {
    //发送请求删除
    try {
      await reqRemoveBrand(row.id as unknown as number);
      //提示
      message.success("删除成功");
      //重新发送请求获取商品的数据
      getBrandList(current, pageSize);
    } catch (error) {
      return Promise.reject(error);
    }
  };

  // 增加商品

  const onFinish = async (values: any) => {
    let teForm = {
      id: RowId,
      tmName: values.tmName,
      logoUrl: values.logoUrl[0].response
        ? values.logoUrl[0].response.data
        : imageUrl,
    };
    console.log(teForm);
    if (teForm.id) {
      try {
        await reqUpdateBrand(teForm);
      } catch (error) {
        console.log(666);
        message.error("更新失败");
        // return Promise.reject("更新失败");
      }
    } else {
      try {
        await reqAddBrand(teForm);
      } catch (error) {
        message.error("添加失败");
        // return Promise.reject("更新失败");
      }
    }
    getBrandList(current, pageSize);
  };

  const getBrandItemType = (row: any) => {
    setIsModalOpen(true);
    setRowId(row.id as string);
    const Row = { ...row };
    setImageUrl(Row.logoUrl);
    form.setFieldsValue({
      tmName: Row.tmName,
      logoUrl: Row.logoUrl,
    });
  };
  // 初始化获取分页列表显示
  useEffect(() => {
    getBrandList(current, pageSize);
  }, []);

  const beforeUpload = (file: RcFile) => {
    const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
    if (!isJpgOrPng) {
      message.error("必须上传图片");
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error("图片不能超过2MB");
    }
    return isJpgOrPng && isLt2M;
  };

  const handleChange: UploadProps["onChange"] = (
    info: UploadChangeParam<UploadFile>
  ) => {
    if (info.file.status === "uploading") {
      setLoading(true);
      return;
    }
    if (info.file.status === "done") {
      setLoading(false);
      setImageUrl(info.file.response.data);
    }
  };

  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>logo</div>
    </div>
  );

  // 提示框相关
  const [isModalOpen, setIsModalOpen] = useState(false);
  // const [open, setOpen] = useState(false);
  const normFile = (e: any) => {
    // console.log("Upload event:", e);
    if (Array.isArray(e)) {
      return e;
    }
    return e?.fileList;
  };

  const showModal = () => {
    setIsModalOpen(true);
    form.resetFields();
    setRowId("");
    setImageUrl("");
  };

  const handleOk = () => {
    form
      .validateFields()
      .then((values) => {
        setImageUrl(values.logoUrl);
        onFinish(values);
        setIsModalOpen(false);
        if (!RowId) {
          message.success("添加成功");
        } else {
          message.success("更新成功");
        }
      })
      .catch((errorInfo) => {
        message.error(errorInfo);
      });
  };

  const handleCancel = () => {
    setIsModalOpen(false);
    form.resetFields();
    setRowId("");
    setImageUrl("");
  };

  // 表格的所有列
  const columns: ColumnsType<BrandItemType> = [
    {
      title: "序号",
      width: 70,
      align: "center",
      render: (_x: any, _y: any, index: number) => {
        return index + 1;
      },
    },
    {
      title: "品牌名称",
      align: "center",
      width: 260,
      dataIndex: "tmName",
    },
    {
      title: "品牌 logo",
      dataIndex: "logoUrl",
      render: (row) => {
        return <img width="70" src={row} alt="" />;
      },
    },
    {
      title: "操作",
      align: "center",
      width: 250,
      render: (row: BrandItemType) => {
        return (
          <>
            <Button
              type="primary"
              size="small"
              icon={<EditOutlined />}
              onClick={() => {
                getBrandItemType(row);
              }}
            >
              修改
            </Button>
            <Button
              onClick={() => removeBrand(row)}
              type="primary"
              danger
              size="small"
              className="ml"
              icon={<DeleteOutlined />}
            >
              删除
            </Button>
          </>
        );
      },
      fixed: "right",
    },
  ];

  return (
    <>
      <Card>
        <Button type="primary" icon={<PlusOutlined />} onClick={showModal}>
          添加
        </Button>
      </Card>

      <Card>
        <Table
          columns={columns}
          dataSource={brandList}
          bordered
          rowKey="id"
          pagination={{
            current,
            pageSize,
            total,
            showQuickJumper: true,
            pageSizeOptions: [5, 10, 15],
            showSizeChanger: true,
            showTotal: (total) => `总共 ${total} 条`,
            onChange: getBrandList,
            onShowSizeChange: getBrandList,
          }}
          scroll={{ x: 1500 }}
          loading={loading}
        />

        <Modal
          title="添加品牌"
          visible={isModalOpen}
          onOk={handleOk}
          onCancel={handleCancel}
          forceRender
        >
          <Form onFinish={onFinish} form={form}>
            <Form.Item
              label="品牌名称"
              name="tmName"
              rules={[{ required: true, message: "品牌名称必须填写" }]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              getValueFromEvent={normFile}
              name="logoUrl"
              label="品牌LOGO"
              valuePropName="logoUrl"
            >
              <Upload
                listType="picture-card"
                className="avatar-uploader"
                showUploadList={false}
                action="/app-dev/admin/product/upload"
                beforeUpload={beforeUpload}
                onChange={handleChange}
              >
                {imageUrl ? (
                  <img src={imageUrl} alt="avatar" style={{ width: "100%" }} />
                ) : (
                  uploadButton
                )}
              </Upload>
            </Form.Item>
          </Form>
        </Modal>
      </Card>
    </>
  );
}
